package com.nd.bdc.presto.connection;


import io.prestosql.jdbc.PrestoConnection;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;

import static io.prestosql.client.OkHttpUtil.basicAuth;

/**
 * <p>Description:  presto的jdbc连接</p>
 *
 * @author ggh
 * @date 2020/6/4
 */
@Component
public class PrestoJdbcClient {

    @Autowired
    PrestoConnProvider prestoConnProvider;

    @Value("${presto.driver}")
    private String driver;

    @Value("${presto.jdbc.url}")
    private String jdbcUrl;

    @Value("${presto.username}")
    private String username;

    @Value("${presto.password}")
    private String password;

    @Value("${presto.ssLKeyStorePassword}")
    private String ssLKeyStorePassword;

    @Value("${presto.ssLKeyStorePath}")
    private String ssLKeyStorePath;

    @Value("${presto.http.url}")
    private String httpUrl;

    private OkHttpClient httpClient = new OkHttpClient();


    public Connection getSchemaConnection(String catalogId, String schemaId) throws SQLException, ClassNotFoundException {
        PrestoConnection conn = prestoConnProvider.getSSLConnection(driver,jdbcUrl,username,password,ssLKeyStorePassword,ssLKeyStorePath);
        if(catalogId != null){
            conn.setCatalog(catalogId);
            if(schemaId != null){
                conn.setSchema(schemaId);
            }
        }
        return conn;
    }

    public Object killQuery(String queryId) throws Throwable {
        okhttp3.Request prestoRequest = new okhttp3.Request.Builder().url(httpUrl + "/v1/query/" + queryId).delete().build();
        Optional<String> prestoUser = Optional.ofNullable(username);
        Response prestoResponse = null;
        if (prestoUser.isPresent()) {
            OkHttpClient.Builder clientBuilder = httpClient.newBuilder();
            clientBuilder.addInterceptor(basicAuth(username, ""));
            prestoResponse = clientBuilder.build().newCall(prestoRequest).execute();
        }
        return prestoResponse;
    }

}
